package com.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hc.common.service.RedisService;
import com.hc.constant.RedisConst;
import com.hc.constant.UserConst;
import com.hc.domain.ReceiveAddr;
import com.hc.domain.User;
import com.hc.mapper.ReceiveAddrMapper;
import com.hc.service.ReceiveAddrService;
import com.hc.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hecai
 * @date 2021/12/22 14:41
 */
@Service
public class ReceiveAddrServiceImpl extends ServiceImpl<ReceiveAddrMapper, ReceiveAddr> implements ReceiveAddrService {

    @Resource
    private RedisService<User> userRedisService;
    @Resource
    private UserService userService;

    @Override
    public boolean saveAddr(ReceiveAddr receiveAddr) {
        User user = UserConst.user;
        int saveRes = baseMapper.insert(receiveAddr);
        if (saveRes == 1) {
            //tb_user表的收件地址数量加1
            user.setReceiveAddrs(user.getReceiveAddrs() + 1);
            userService.updateById(user);
            //更新缓存中用户的信息
            userRedisService.set(RedisConst.User + "::" + user.getId(), user);
            return true;
        }
        return false;
    }

    @Override
    public List<ReceiveAddr> getReceiveAddrs() {
        User user = UserConst.user;
        QueryWrapper<ReceiveAddr> queryWrapper = new QueryWrapper<ReceiveAddr>()
                .eq("user_id", user.getId())
                .orderByDesc("update_time");
        List<ReceiveAddr> receiveAddrList = baseMapper.selectList(queryWrapper);
        //如果是默认，将其放在最前面
        for (int i = 0; i < receiveAddrList.size(); i++) {
            if (receiveAddrList.get(i).getIsDefault()) {
                receiveAddrList.add(0, receiveAddrList.get(i));
                receiveAddrList.remove(i + 1);
            }
        }
        return receiveAddrList;
    }
}
